package com.sxbbc.seller.service;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.regular.RpxUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.seller.util.BusinessSession;



@Service
public class BusinessService {
	
	@Autowired
	private IBLoginService bLoginService;
	@Autowired
	private IBRolesService bRolesService;
	@Autowired
	private IBMenusService bMenusService;
	@Autowired
    private BBusinessService bBusinessService;
	@Autowired
    private IAddressService addressService;
	@Autowired
	private ISysCashDetailsService sysCashDetailsService;
	
    /**
     * 商家 去登录操作
     *
     * @param request   session
     * @param login     登录名
     * @param password  密码
     * @param validCode 验证码
     * @return 登录状态
     * @author YQQ
     */
    public RestResponse doLogin(HttpServletRequest request, String login, String password, String validCode) {
        String valid = BusinessSession.getValidCode(request);
        CalcuUtils calcu = CalcuUtils.getInstance();
        if (StringUtils.isBlank(login)) {
            return GetRest.getFail("请输入登录账号");
        }
        if (StringUtils.isBlank(password)) {
            return GetRest.getFail("请输入密码");
        }
        //TODO  项目发布需要取消该注释
        if (StringUtils.isBlank(validCode)) {
            return GetRest.getFail("请输入验证码");
        }
        if (!StringUtils.equalsIgnoreCase(valid, validCode)) {
            return GetRest.getFail("验证码不正确");
        }
        BLogin bLogin = bLoginService.selectByLogin(login);
        if (bLogin == null) {
            return GetRest.getFail("该账号不存在");
        }
        if (!calcu.isEquals(bLogin.getStatus(), StaticUtils.STATUS_YES)) {
            return GetRest.getFail("该账号已被冻结");
        }
        String mdPass = DESEncode.getInstance().encrypt(password);
        if (!StringUtils.equals(bLogin.getPassWord(), mdPass)) {
            return GetRest.getFail("密码不正确");
        }

        //拥有菜单权限
        List<BMenus> menusList =null;
        if(bLogin.getIsPrimaryLogin().equals(StaticUtils.STATUS_NO)){
            BRoles role = bRolesService.getById(bLogin.getRoleId());
            if (role == null) {
                return GetRest.getFail("用户所属角色不存在");
            }
            if (!calcu.isEquals(role.getStatus(),StaticUtils.STATUS_YES)) {
                return GetRest.getFail("用户所属角色已被冻结");
            }

            List<Integer> list = calcu.getIntegerList(role.getMenuIds().split(","));
            if (list.isEmpty() || list.size() < 1) {
                return GetRest.getFail("当前角色没有菜单权限");
            }
            QueryWrapper<BMenus> wrapper = new QueryWrapper<>();
            wrapper.in("id",list);
            menusList = bMenusService.queryMenusList(wrapper);
            //获取并设置商家编码
        }else{
            QueryWrapper<BMenus> wrapper = new QueryWrapper<>();
            wrapper.in("status",StaticUtils.STATUS_YES);
            menusList = bMenusService.queryMenusList(wrapper);
        }

        BBusiness bBusiness = bBusinessService.getById(bLogin.getBid());
        BusinessSession.setBusinessCode(request,bBusiness.getBusinessCode());
        BusinessSession.setBid(request,bBusiness.getId());
        BusinessSession.setMenuList(request,menusList);
        BusinessSession.setBLogin(request, bLogin);
        BusinessSession.setLoginID(request, bLogin.getId());;
        BusinessSession.setRoleid(request, bLogin.getRoleId());
        BusinessSession.setLoginName(request, bLogin.getNickName());
        BusinessSession.setMenuUrl(request, menusList.stream().map(BMenus :: getUrl).collect(Collectors.toList()));
        return GetRest.getSuccess("登录成功");
    }

    /**
     * 拿到拼接后的地址
     * @param proId 省id
     * @param cityId 城市id
     * @param areaId 区域id
     * @author leehao
     * @return 字符串
     */
    public String getAddrName(Integer proId, Integer cityId, Integer areaId) {
        StringBuffer name = new StringBuffer();
        Address address = addressService.getById(proId);
        if (address != null) {
            name = name.append(address.getName());
        }
        address = addressService.getById(cityId);
        if (address != null) {
            name = name.append(" ").append(address.getName());
        }
        address = addressService.getById(areaId);
        if (address != null) {
            name = name.append(" ").append(address.getName());
        }
        return name.toString();
    }

    /**
     * 处理店铺提现
     * @param cashDetail
     * @return
     */
	public RestResponse handleBusinessCashApply(SysCashDetails cashDetail) {
		BBusiness business = bBusinessService.getById(cashDetail.getTargetId());
		if (business == null) {
			return GetRest.getFail("获取店铺信息失败");
		}
		RestResponse result = sysCashDetailsService.handleCashApply(cashDetail);
		return result;
	}

	/**
	 * 通过主键查询店铺
	 * @param bid
	 * @return BBusiness
	 */
	public BBusiness getById(Integer bid) {
		BBusiness business = bBusinessService.getById(bid);
	    List<String> coverUrlList = new ArrayList<String>();
		if (!StringUtils.isEmpty(business.getCoverUrl())) {
			JSONArray jsonArray = JSON.parseArray(business.getCoverUrl());
			StringBuffer coverUrl = new StringBuffer();
			for (int i = 0; i<jsonArray.size(); i++) {
				String str = "";
				JSONObject jsonObject = (JSONObject) JSONObject.toJSON(jsonArray.get(i));
				str = (String) jsonObject.get("url");
				coverUrl.append(str);
				if (i < jsonArray.size()-1) {
					coverUrl.append(",");
				}
				coverUrlList.add(str);
			}
			business.setCoverUrl(coverUrl.toString());
			business.setCoverUrlList(coverUrlList);
		}
		return business;
	}

	/**
	 * 编辑店铺信息
	 * @param business
	 * @return
	 */
	public RestResponse editBusiness(BBusiness business) {
		BBusiness queryBusiness = bBusinessService.getById(business.getId());
		if (queryBusiness == null) {
			return GetRest.getFail("店铺不存在，保存失败");
		}
		RpxUtils regex = RpxUtils.getInstance();
		if (StringUtils.isBlank(business.getNickName())) {
            return GetRest.getFail("请输入商家名称");
        }
        if (StringUtils.isBlank(business.getRealName())) {
            return GetRest.getFail("请输入真实姓名");
        }
        if (StringUtils.isBlank(business.getLinkPhone())) {
            return GetRest.getFail("请输入商家联系电话");
        }
        if (business.getId() == null && StringUtils.isBlank(business.getPhone())) {
            return GetRest.getFail("请输入联系电话");
        }
        if (!StringUtils.equals(regex.validPhone(business.getLinkPhone()), "")) {
            return GetRest.getFail("联系电话：" + regex.validPhone(business.getLinkPhone()));
        }
        if (StringUtils.isBlank(business.getLicenseCode())) {
            return GetRest.getFail("请输入营业执照号码");
        }
        if (business.getIndustryId() == null || business.getIndustryDetailId() == null) {
            return GetRest.getFail("请选择行业");
        }
		boolean result = bBusinessService.updateById(business);
		if (result) {
			return GetRest.getSuccess("保存成功");
		}
		return GetRest.getFail("保存失败");
	}

}
